package lin.zhihong.red.deadlock;

import java.util.concurrent.locks.ReentrantLock;

public class DeadlockApplication {

    public static void main(String[] args) {

        final ReentrantLock lockA = new ReentrantLock();
        final ReentrantLock lockB = new ReentrantLock();

        lockA.lock();
        System.out.println(DateUtil.getYYYYMMDDhhmmss() + " Main线程获取到lockA。");
        try {

            new Thread(new Runnable() {
                public void run() {
                    lockB.lock();
                    System.out.println(DateUtil.getYYYYMMDDhhmmss() + " Thread线程获取到lockB。");
                    try {
                        try {
                            Thread.sleep(3 * 1000);
                        } catch (InterruptedException ignore) {
                            //
                        }
                        System.out.println(DateUtil.getYYYYMMDDhhmmss() + " Thread线程3秒后，尝试获取lockA。");

                        lockA.lock();
                        try {

                        } finally {
                            lockA.unlock();
                        }

                    } finally {
                        lockB.unlock();
                    }
                }
            }).start();

            try {
                Thread.sleep(5 * 1000);
            } catch (InterruptedException ignore) {
                //
            }
            System.out.println(DateUtil.getYYYYMMDDhhmmss() + " Main线程休眠5秒后，尝试获取lockB。");

            lockB.lock();
            try {

            } finally {
                lockB.unlock();
            }

        } finally {
            lockA.unlock();
        }
    }
}
